package cn.itcast.web.controller.cargo;

import cn.itcast.domain.cargo.Export;
import cn.itcast.domain.cargo.ExportProduct;
import cn.itcast.domain.cargo.ExportProductExample;
import cn.itcast.domain.system.User;
import cn.itcast.service.cargo.ExportProductService;
import cn.itcast.service.cargo.ExportService;
import cn.itcast.web.controller.BaseController;
import cn.itcast.web.utils.BeanMapUtils;
import com.alibaba.dubbo.config.annotation.Reference;
import lombok.extern.slf4j.Slf4j;
import net.sf.jasperreports.engine.JREmptyDataSource;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletOutputStream;
import javax.sql.DataSource;
import java.io.InputStream;
import java.util.*;
import java.util.concurrent.ForkJoinPool;


@Controller
@RequestMapping("/cargo/export")
@Slf4j
public class PdfController extends BaseController {

    /**
     * PDF导出（1）入门 + 中文处理
     */
    @RequestMapping("/exportPdf12")
    public void exportPdf12() throws Exception {
        //1. 获取pdf模板文件流
        InputStream in =
                session.getServletContext()
                        .getResourceAsStream("/jasper/test02.jasper");
        //2. 创建JasperPrint对象，用于往模板中填充数据
        // 参数1：jasper文件流
        // 参数2：填充数据用途，通过map填充数据
        // 参数3：填充数据用途，通过数据源填充数据
        JasperPrint jasperPrint =
                JasperFillManager.fillReport(in, new HashMap<>(), new JREmptyDataSource());

        //3. 导出PDF
        // 参数1：jasperPrint对象
        // 参数2：把jasper文件流，写入到哪个输出流中。现在写入response输出流
        JasperExportManager.exportReportToPdfStream(jasperPrint, response.getOutputStream());
    }


    /**
     * PDF导出（3）填充数据 A map填充
     */
    @RequestMapping("/exportPdf3")
    public void exportPdf3() throws Exception {
        //1. 获取pdf模板文件流
        InputStream in =
                session.getServletContext()
                        .getResourceAsStream("/jasper/test03_parameter.jasper");
        // 构造数据: map的key要对应模板中的Parameters参数名称
        Map<String, Object> map = new HashMap<>();
        map.put("userName", "张大神");
        map.put("email", "zds@export.com");
        map.put("deptName", "开发部");
        map.put("companyName", "SaasExport货代公司");

        //2. 创建JasperPrint对象，用于往模板中填充数据
        JasperPrint jasperPrint =
                JasperFillManager.fillReport(in, map, new JREmptyDataSource());

        //3. 导出PDF
        JasperExportManager.exportReportToPdfStream(jasperPrint, response.getOutputStream());
    }


    @Autowired
    private DataSource dataSource;

    /**
     * PDF导出（4）填充数据 B 数据源填充 JDBC数据源
     */
    @RequestMapping("/exportPdf4")
    public void exportPdf4() throws Exception {
        //1. 获取pdf模板文件流
        InputStream in =
                session.getServletContext()
                        .getResourceAsStream("/jasper/test04_jdbc.jasper");

        //2. 创建JasperPrint对象，用于往模板中填充数据
        JasperPrint jasperPrint =
                JasperFillManager.fillReport(in, null, dataSource.getConnection());

        //3. 导出PDF
        JasperExportManager.exportReportToPdfStream(jasperPrint, response.getOutputStream());
    }


    /**
     * PDF导出（5）填充数据 B 数据源填充 JavaBean填充
     */
    @RequestMapping("/exportPdf5")
    public void exportPdf5() throws Exception {
        //1. 获取pdf模板文件流
        InputStream in =
                session.getServletContext()
                        .getResourceAsStream("/jasper/test05_javabean.jasper");
        // 构造集合: 集合中对象的属性或者list集合中map的key，一定要与Fields名称一致
        //List<User> list = new ArrayList<>();
        List<Map<String, Object>> list = new ArrayList<>();
        for (int i = 1; i < 6; i++) {
            Map<String, Object> map = new HashMap<>();
            map.put("userName", "张大神" + i);
            map.put("email", "zds@export.com");
            map.put("deptName", "开发部");
            map.put("companyName", "SaasExport货代公司");
            list.add(map);
        }

        // 创建javabena数据源对象
        JRBeanCollectionDataSource dataSource = new JRBeanCollectionDataSource(list);

        //2. 创建JasperPrint对象，用于往模板中填充数据
        JasperPrint jasperPrint =
                JasperFillManager.fillReport(in, null, dataSource);

        //3. 导出PDF
        JasperExportManager.exportReportToPdfStream(jasperPrint, response.getOutputStream());
    }


    /**
     * PDF导出（6）分组报表
     */
    @RequestMapping("/exportPdf6")
    public void exportPdf6() throws Exception {
        //1. 获取pdf模板文件流
        InputStream in =
                session.getServletContext()
                        .getResourceAsStream("/jasper/test06_group.jasper");
        // 构造集合: 集合中对象的属性或者list集合中map的key，一定要与Fields名称一致
        List<Map<String, Object>> list = new ArrayList<>();
        for (int j = 1; j <= 2; j++) { // 企业
            for (int i = 1; i < 6; i++) {
                Map<String, Object> map = new HashMap<>();
                map.put("userName", "张大神" + i);
                map.put("email", "zds@export.com");
                map.put("deptName", "开发部");
                map.put("companyName", "SaasExport货代公司" + j);
                list.add(map);
            }
        }

        // 创建javabena数据源对象
        JRBeanCollectionDataSource dataSource = new JRBeanCollectionDataSource(list);

        //2. 创建JasperPrint对象，用于往模板中填充数据
        JasperPrint jasperPrint =
                JasperFillManager.fillReport(in, null, dataSource);

        //3. 导出PDF
        JasperExportManager.exportReportToPdfStream(jasperPrint, response.getOutputStream());
    }


    /**
     * PDF导出（7）图表统计
     */
    @RequestMapping("/exportPdf7")
    public void exportPdf7() throws Exception {
        //1. 获取pdf模板文件流
        InputStream in =
                session.getServletContext()
                        .getResourceAsStream("/jasper/test07_chart.jasper");
        // 构造集合: 集合中对象的属性或者list集合中map的key，一定要与Fields名称一致
        List<Map<String, Object>> list = new ArrayList<>();
        for (int i = 1; i < 6; i++) {
            Map<String, Object> map = new HashMap<>();
            map.put("title", "厂家" + i);
            map.put("value", new Random().nextInt(100));
            list.add(map);
        }

        // 创建javabena数据源对象
        JRBeanCollectionDataSource dataSource = new JRBeanCollectionDataSource(list);

        //2. 创建JasperPrint对象，用于往模板中填充数据
        JasperPrint jasperPrint =
                JasperFillManager.fillReport(in, null, dataSource);

        //3. 导出PDF
        JasperExportManager.exportReportToPdfStream(jasperPrint, response.getOutputStream());
    }


    @Reference
    private ExportService exportService;
    @Reference
    private ExportProductService exportProductService;

    /**
     * PDF导出（8）导出报运详情
     */
    @RequestMapping("/exportPdf")
    public void exportPdf(String id) throws Exception {
        //1. 获取pdf模板文件流
        InputStream in =
                session.getServletContext()
                        .getResourceAsStream("/jasper/export.jasper");

        //A. 根据报运单id查询
        Export export = exportService.findById(id);
        // 对象转换为map
        Map<String, Object> map = BeanMapUtils.beanToMap(export);

        //B. 根据报运单id查询商品
        ExportProductExample example = new ExportProductExample();
        example.createCriteria().andExportIdEqualTo(id);
        List<ExportProduct> list = exportProductService.findAll(example);

        // 创建javabena数据源对象
        JRBeanCollectionDataSource dataSource = new JRBeanCollectionDataSource(list);

        //2. 创建JasperPrint对象，用于往模板中填充数据
        JasperPrint jasperPrint =
                JasperFillManager.fillReport(in, map, dataSource);

        //3. 导出PDF
        response.setCharacterEncoding("UTF-8");
        response.setHeader("content-disposition","attachment;fileName=export.pdf");
        ServletOutputStream out = response.getOutputStream();
        JasperExportManager.exportReportToPdfStream(jasperPrint, out);
        out.close();
    }
}